import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/layout',
    component: () => import('../views/layout.vue'),
    children: [
      {
        path: '/index',
        component: () => import('../views/index.vue')
      },
      {
        path:'/menu',
        component:()=>import('../views/menu.vue')
      },
      {
        path:'/role',
        component:()=>import('../views/role.vue')
      },
      {
        path:'/user',
        component:()=>import('../views/user.vue')
      },
      {
        path:'/cate',
        component:()=>import('../views/cate.vue')
      },
      {
        path:'/space',
        component:()=>import('../views/space.vue')
      },
      {
        path:'/goods',
        component:()=>import('../views/goods.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../views/login.vue')
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach(function (to, from, next) {
  //设置白名单
  
  const no_login_list = ['/login']
  if (no_login_list.indexOf(to.path) === -1) {
    
    //获取localStorage中的token，校验是否存在
    var tokenString = localStorage.getItem('logindata') || '{}'
    var token = JSON.parse(tokenString).token
    if (token) {
      var menu_list = JSON.parse(tokenString).menus_url
      menu_list.push('/index')
      menu_list.push('/login')
      if(menu_list.indexOf(to.path)===-1){
        next('/index')
      }else {
        next()
      } 
    }else{
      next('/login')
    }
  } else {
    next()
  }
})

export default router
